package adt;

import java.util.ArrayList;

import util.Params;

/**
 * A sentence data structure.
 * 
 * 用于表示一个句子的对象。
 * 
 * @author Tianyu Xu
 * 
 */
public class Sentence {
	/**
	 * 储存句子中每个字符的列表
	 */
	private ArrayList<Word> wordList = null;
	/**
	 * 储存句子中每个谓词起止位置的列表
	 */
	private PredPos[] predPosList = null;

	/**
	 * 构造一个空句子
	 */
	public Sentence() {
		wordList = new ArrayList<Word>();
	}

	/**
	 * Add a word to the word list of the sentence. If the word is also in a
	 * predicate, add it to the predicate list of the sentence.
	 * 
	 * 向句子的字符列表中添加一个字符。如果该字符同时属于某谓词，则同时将其添加到谓词列表中。
	 * 
	 * @param w
	 *            要添加的单词
	 */
	public void addWord(Word w) {
		wordList.add(w);

		// 如果该字属于某个谓词
		if (w.getPredIndexList().size() != 0) {
			// 创建正确长度的谓词位置列表
			if (predPosList == null) {
				predPosList = new PredPos[w.getSrlTagList().size()];
			}
			// 对于该汉字属于的每个谓词
			for (Integer predIndex : w.getPredIndexList()) {
				// 获取当前字符在句中的索引
				int wordIndex = wordList.size() - 1;
				if (predPosList[predIndex] == null) {
					predPosList[predIndex] = new PredPos(wordIndex);
				} else {
					predPosList[predIndex].appendIndex(wordIndex);
				}
			}
		}
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (Word w : wordList) {
			sb.append(w.getCh());
		}
		return sb.toString();
	}

	/**
	 * Returns a string representing of the sentence. Only the "pure" words are
	 * included in the string.
	 * 
	 * 返回句子的字符串表示。左右填充字符不会被输出。
	 * 
	 * @return 不带左右填充字符的句子表示
	 */
	public String toStrWithoutPaddings() {
		StringBuilder sb = new StringBuilder();
		int leftIndex = Params.PADDING_SIZE, rightIndex = wordList.size() - Params.PADDING_SIZE;

		for (int i = leftIndex; i < rightIndex; i++) {
			sb.append(wordList.get(i).getCh());
		}
		return sb.toString();
	}

	/**
	 * 获得 i 处的字符
	 * 
	 * @param i
	 *            字符索引，包含左右 paddings
	 * @return 在 i 处的字符对象
	 */
	public Word wordAt(int i) {
		return wordList.get(i);
	}

	/**
	 * 获取句子的谓词起止位置列表
	 * 
	 * @return 句子的谓词起止位置列表
	 */
	public PredPos[] getPredPosList() {
		return predPosList;
	}

	/**
	 * Return the length of the sentence (with paddings). If you want the length
	 * without paddings, call lengthWithoutPaddings() method.
	 * 
	 * 返回句子长度（包含左右填充）。若需调用不含左右填充的句子长度，调用lengthWithoutPaddings()方法。
	 * 
	 * @return the length of the sentence (with paddings)
	 */
	public int length() {
		return wordList.size();
	}

	/**
	 * Return the length of the sentence (without paddings). If you want the
	 * length with paddings, call length() method.
	 * 
	 * 返回句子长度（不包含左右填充）。若需获得含左右填充的句子长度，调用length()方法。
	 * 
	 * @return the length of the sentence (with paddings)
	 */
	public int lengthWithoutPaddings() {
		return wordList.size() - Params.WINDOW_SIZE + 1;
	}

}
